<?php

namespace App\Store\Controllers\Order;

use App\Common\Services\CommonExcelExport;
use App\Store\Services\Member\CommonMember;
use App\Store\Services\Message\WxaccountMessage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Member\MemberBalanceChangelog;
use App\Store\Models\Order\OrderMaintenance;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Account\Account;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Member\Member;
use App\Store\Models\Basic\PaytypeList;
use App\Store\Services\Financial;
use App\Store\Services\Order\OrderSales;
use Illuminate\Support\Facades\DB;
use App\Store\Validate\Order\OrderMaintenance as ValidateOrderOrderMaintenance;
use Maatwebsite\Excel\Facades\Excel;


use App\Store\Validate\Order\OrderSales as ValidateOrderOrderSales;

use App\Store\Services\Order\OrderMaintenance as ServicesOrderOrderMaintenance;

/**
 * 维修开单
 */
class OrderMaintenanceController extends Controller
{
    /**
     * 开单
     */
    public function dopostorder(Request $request)
    {

        $req_data = $request->only([
            'mobile', 'real_name', 'mem_card_no', 'lunar_bdate', 'solar_bdate', 'points_current', 'money', 'balance_money', 'pay_money', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id','mixed_payment', 'order_at', 'desc', 'issendpoints', 'remark',
        ]);
        if (intval($req_data['money']) <= 0 || intval($req_data['money']) != (intval($req_data['balance_money']) + intval($req_data['pay_money']))) {
            return response()->json(['code' => '001', 'msg' => '付款金额参数有误']);
        }
        $Validate = new ValidateOrderOrderMaintenance();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        if (intval($req_data['pay_money']) > 0) {
            $Validate = new ValidateOrderOrderMaintenance('paytypecheck');
            if (!$Validate->check($req_data)) {
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
            }
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $orderdata = [
            'money' => $req_data['money'],
            'balance_money' => $req_data['balance_money'],
            'pay_money' => $req_data['pay_money'],
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2'=>isset($req_data['shopping_account_id2'])?intval($req_data['shopping_account_id2']):0,
            'classesset_id' =>isset($req_data['classesset_id']) ?  intval($req_data['classesset_id']):0,
            'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']) ,
            'order_at' => isset($req_data['order_at']) ?strtotime($req_data['order_at']):time(),
            'desc' => $req_data['desc'],
            'issendpoints' => isset($req_data['issendpoints']) ? intval($req_data['issendpoints']) : 1,
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : ''
        ];
        // $orderdata['order_at'] = strtotime($orderdata['order_at']);
        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if ($store_ids) { //权限控制
            if (is_array($store_ids)) { //获取当前权限下的门店

                return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }

        if(isset($req_data['mobile']) && !empty($req_data['mobile'])){
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'],'is_del'=>1])->first();
            if (!$meminfo) {
                if ($orderdata['balance_money'] > 0) {
                    return response()->json(['code' => '001', 'msg' => '新建账户预存金额为0，不可使用预存金额']);
                }
                $memdata = [
                    'cp_id' => $cp_id,
                    'store_id' => $current_store_id,
                    'mobile' => $req_data['mobile'],
                    'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                    'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                    'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                    'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                    'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                    'create_at' => time(),
                    'update_at' => time(),
                    'create_account_id' => $accountinfo['id'],
                    'update_account_id' => $accountinfo['id'],
                    'create_account_real_name' => $accountinfo['real_name'],
                    'update_account_real_name' => $accountinfo['real_name'],
                ];
                $ins_mem_id = Member::create($memdata);
                CommonMember::setMemInitPoints($request, $ins_mem_id);
            } else {
                if ($orderdata['balance_money'] > $meminfo->pre_money) {
                    return response()->json(['code' => '001', 'msg' => '预存金额不足，请修改后重新下单']);
                }
            }
            $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'],'is_del'=>1])->first();
        }else{

            $meminfo =json_decode(json_encode(['id'=>0,'pre_money'=>0,'pointstobalance'=>0]));
        }


        $orderdata['mem_id'] = $meminfo->id;

        $orderdata['cp_id'] = $cp_id;
        $orderdata['store_id'] = $current_store_id;
        $orderdata['order_sn'] = StoreCommon::createOrderSn();
        $orderdata['pay_type_name'] = $req_data['pay_type_id'] == -1 ?'混合支付':PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name');

        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();
        $orderid=OrderMaintenance::create($orderdata)->id;


        $printdata=$request->is_print==1 ? ServicesOrderOrderMaintenance::getOrderPrintData($orderid):[];


        return response()->json(['code' => '000', 'msg' => '开单成功','data'=>$printdata]);
    }

    /**
     * 挂单
     */
    public function dopostordermaker(Request $request)
    {

        $req_data = $request->only([
            'mobile', 'real_name', 'mem_card_no', 'lunar_bdate', 'solar_bdate', 'points_current', 'money', 'balance_money', 'pay_money', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'desc', 'issendpoints', 'remark','mixed_payment'
        ]);
        if (intval($req_data['money']) <= 0 || intval($req_data['money']) != (intval($req_data['balance_money']) + intval($req_data['pay_money']))) {
            return response()->json(['code' => '001', 'msg' => '付款金额参数有误']);
        }
        $Validate = new ValidateOrderOrderMaintenance();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        if (intval($req_data['pay_money']) > 0) {
            $Validate = new ValidateOrderOrderMaintenance('paytypecheck');
            if (!$Validate->check($req_data)) {
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
            }
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $orderdata = [
            'money' => $req_data['money'],
            'balance_money' => $req_data['balance_money'],
            'pay_money' => $req_data['pay_money'],
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2' => $req_data['shopping_account_id2'],
            'classesset_id' => $req_data['classesset_id'],
            'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']) ,
            'order_at' => isset($req_data['order_at']) ?strtotime($req_data['order_at']):time(),
            'desc' => $req_data['desc'],
            'issendpoints' => $req_data['issendpoints'],
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : ''
        ];
        // $orderdata['order_at'] = strtotime($orderdata['order_at']);
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'],'is_del'=>1])->first();
        $current_store_id = 0;
        $store_ids = $accountinfo['store_ids'];
        if ($store_ids) { //权限控制
            if (is_array($store_ids)) { //获取当前权限下的门店

                return response()->json(['code' => '001', 'msg' => '请使用店长或店员账号']);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $current_store_id = intval($store_ids);
            }
        }
        if (!$meminfo) {
            if ($orderdata['balance_money'] > 0) {
                return response()->json(['code' => '001', 'msg' => '新建账户预存金额为0，不可使用预存金额']);
            }
            $memdata = [
                'cp_id' => $cp_id,
                'store_id' => $current_store_id,
                'mobile' => $req_data['mobile'],
                'real_name' => isset($req_data['real_name']) ? $req_data['real_name'] : '',
                'mem_card_no' => isset($req_data['mem_card_no']) ? $req_data['mem_card_no'] : '',
                'lunar_bdate' => isset($req_data['lunar_bdate']) ? $req_data['lunar_bdate'] : '',
                'solar_bdate' => isset($req_data['solar_bdate']) ? $req_data['solar_bdate'] : '',
                'points_current' => isset($req_data['points_current']) ? intval($req_data['points_current']) : 0,
                'create_at' => time(),
                'update_at' => time(),
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
            ];
            Member::create($memdata);
        } else {
            if ($orderdata['balance_money'] > $meminfo->pre_money) {
                return response()->json(['code' => '001', 'msg' => '预存金额不足，请修改后重新下单']);
            }
        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'],'is_del'=>1])->first();
        $orderdata['mem_id'] = $meminfo->id;

        $orderdata['cp_id'] = $cp_id;
        $orderdata['store_id'] = $current_store_id;
        $orderdata['order_sn'] = date('YmdHis') . $cp_id . $current_store_id . rand(1000, 9999);
        $orderdata['pay_type_name'] = $req_data['pay_type_id'] == -1 ?'混合支付':PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name');

        $orderdata['create_account_id'] = $accountinfo['id'];
        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['create_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['create_at'] = time();
        $orderdata['update_at'] = time();
        // $orderdata['is_maker'] = 2;
        OrderMaintenance::create($orderdata);

        return response()->json(['code' => '000', 'msg' => '挂单成功']);
    }

    /**
     * 挂单支付
     */
    public function doordermakerpay(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }
        // if ($info->is_maker != 2) {
        //     return response()->json(['code' => '001', 'msg' => '该订单不是挂单状态']);
        // }
        OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_maker' => 1, 'update_at' => time()]);
        return response()->json(['code' => '000', 'msg' => '订单支付成功']);
    }

    /**
     * 订单列表
     */

    public function getorderlist(Request $request)
    {
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        if ($accountinfo['type'] == 11) {
            $training = StoreCommon::gettraining($request);
            if ($training['training_min'] == 0 && $training['training_max'] == 0) {
                return response()->json(['code' => '001', 'msg' => '培训账号，请先设置公司培训上下限']);
            }
            $request->training_min = $training['training_min'];
            $request->training_max = $training['training_max'];
        }
        $list = OrderMaintenance::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);
    }

    /**
     * 订单详情
     */
    public function getinfo(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderMaintenance::with(['memberinfo','shoppingaccountinfo1','shoppingaccountinfo2','storeinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => ['info' => $info]]);
    }

    /**
     * 订单编辑
     */
    public function doorderedit(Request $request)
    {
        $req_data = $request->only([
            'id', 'money', 'balance_money', 'pay_money', 'shopping_account_id1', 'shopping_account_id2', 'classesset_id', 'pay_type_id', 'order_at', 'desc', 'issendpoints', 'remark','mixed_payment',
        ]);
        $id = $request->id ?? 0;
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }

        // if ($info->is_maker != 1) {
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可编辑']);
        // }
        if (intval($req_data['money']) <= 0 || intval($req_data['money']) != (intval($req_data['balance_money']) + intval($req_data['pay_money']))) {
            return response()->json(['code' => '001', 'msg' => '付款金额参数有误']);
        }

        $Validate = new ValidateOrderOrderMaintenance('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        if (intval($req_data['pay_money']) > 0) {
            $Validate = new ValidateOrderOrderMaintenance('paytypecheck');
            if (!$Validate->check($req_data)) {
                return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
            }
        }
        $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id,'is_del'=>1])->first();
        if ($req_data['balance_money'] > $meminfo->pre_money) {
            return response()->json(['code' => '001', 'msg' => '预存金额不足，请修改后重新下单']);
        }
        $orderdata = [
            'money' => $req_data['money'],
            'balance_money' => $req_data['balance_money'],
            'pay_money' => $req_data['pay_money'],
            'shopping_account_id1' => $req_data['shopping_account_id1'],
            'shopping_account_id2' => $req_data['shopping_account_id2'],
            'classesset_id' => $req_data['classesset_id'],
            'pay_type_id' => isset($req_data['pay_type_id']) ? intval($req_data['pay_type_id']) : 0,
            'mixed_payment' => (empty($req_data['mixed_payment']) || $req_data['mixed_payment'] == '{}') ? '' : json_encode($req_data['mixed_payment']) ,
            'order_at' => isset($req_data['order_at']) ?strtotime($req_data['order_at']):time(),
            'desc' => $req_data['desc'],
            'issendpoints' => $req_data['issendpoints'],
            'remark' => isset($req_data['remark']) ? $req_data['remark'] : ''
        ];
        // $orderdata['order_at'] = strtotime($orderdata['order_at']);
        $orderdata['pay_type_name'] = $req_data['pay_type_id'] == -1 ?'混合支付':PaytypeList::where(['id' => $req_data['pay_type_id']])->value('paytype_name');

        $orderdata['update_account_id'] = $accountinfo['id'];
        $orderdata['update_account_real_name'] = $accountinfo['real_name'];
        $orderdata['update_at'] = time();
        OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update($orderdata);

        return response()->json(['code' => '000', 'msg' => '订单编辑成功']);
    }

    /**
     * 审核通过
     */
    public function doorderauditsuccess(Request $request)
    {
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        $info = OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }

        // if ($info->is_maker != 1) {
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }

        $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id,'is_del'=>1])->first();


        if ($info->balance_money > 0) {
            if ($info->balance_money > $meminfo->pre_money) {
                return response()->json(['code' => '001', 'msg' => '预存金额不足']);
            }
        }




        DB::beginTransaction();
        try {

            if ($info->mem_id>0 && $info->balance_money > 0) {
                $data = [
                    'cp_id' => $cp_id,
                    'mem_id' => $info->mem_id,
                    'type' => 12,
                    'store_id' => $info->store_id,
                    'change_val' => -$info->balance_money,
                    'change_before' => $meminfo->pre_money,
                    'change_after' => $meminfo->pre_money - $info->balance_money,
                    'sales_account_id' => $info->shopping_account_id1,
                    'loginfo' => json_encode(['title' => '维修开单']),
                    'create_account_id' => $info->create_account_id,
                    'update_account_id' => $info->update_account_id,
                    'create_account_real_name' => $info->create_account_real_name,
                    'update_account_real_name' => $info->update_account_real_name,
                    'create_at' => time(),
                    'update_at' => time(),
                    'remark' => $info->remark,
                ];
                MemberBalanceChangelog::create($data);
                Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'pre_money' => DB::raw('pre_money - ' . $info->balance_money),
                ]);
            }


            OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);


            $info->mem_id>0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                'shopping_times'=>DB::raw('shopping_times + 1 '),
                'shopping_money_total'=>DB::raw('shopping_money_total + '.$info->pay_money),
                'avg_shopping_money'=>intval(($meminfo->shopping_money_total+$info->pay_money)/($meminfo->shopping_times+1)),
                'max_shopping_money'=>($info->pay_money>$meminfo->max_shopping_money?$info->pay_money:$meminfo->max_shopping_money),
                'min_shopping_money'=>($info->pay_money<$meminfo->min_shopping_money?$info->pay_money:$meminfo->min_shopping_money),
                'last_shopping_at'=>$info->create_at
            ]);


            //计算绩效？
            //订单成功发送短信
            // $info->mem_id>0 && WxaccountMessage::sendwx($cp_id, $info->mem_id, 'order'); //收支流水
            Financial::createMoneyLog($cp_id,$info,$info->pay_money,-1);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);
    }


    public function doorderauditsuccessmore(Request $request){
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);



        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];



        $info_more_arr = OrderMaintenance::where(['cp_id' => $cp_id, 'audit_status'=>1])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核订单']);
        }







        DB::beginTransaction();
        try {

            foreach($info_more_arr as $info){
                $id=$info->id;
                $meminfo = Member::where(['cp_id' => $cp_id, 'id' => $info->mem_id,'is_del'=>1])->first();
                $msgtitle='订单：'.$info->order_sn;


                if ($info->balance_money > 0) {
                    if ($info->balance_money > $meminfo->pre_money) {
                        // return response()->json(['code' => '001', 'msg' => '预存金额不足']);
                        throw new \Exception($msgtitle.'预存金额不足');
                    }
                }

                if ($info->mem_id>0 && $info->balance_money > 0) {
                    $data = [
                        'cp_id' => $cp_id,
                        'mem_id' => $info->mem_id,
                        'type' => 12,
                        'store_id' => $info->store_id,
                        'change_val' => -$info->balance_money,
                        'change_before' => $meminfo->pre_money,
                        'change_after' => $meminfo->pre_money - $info->balance_money,
                        'sales_account_id' => $info->shopping_account_id1,
                        'loginfo' => json_encode(['title' => '维修开单']),
                        'create_account_id' => $info->create_account_id,
                        'update_account_id' => $info->update_account_id,
                        'create_account_real_name' => $info->create_account_real_name,
                        'update_account_real_name' => $info->update_account_real_name,
                        'create_at' => time(),
                        'update_at' => time(),
                        'remark' => $info->remark,
                    ];
                    MemberBalanceChangelog::create($data);
                    Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                        'pre_money' => DB::raw('pre_money - ' . $info->balance_money),
                    ]);
                }


                OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 2, 'audit_at' => time()]);


                $info->mem_id>0 && Member::where(['id' => $info->mem_id, 'cp_id' => $cp_id, 'is_del' => 1])->update([
                    'shopping_times'=>DB::raw('shopping_times + 1 '),
                    'shopping_money_total'=>DB::raw('shopping_money_total + '.$info->pay_money),
                    'avg_shopping_money'=>intval(($meminfo->shopping_money_total+$info->pay_money)/($meminfo->shopping_times+1)),
                    'max_shopping_money'=>($info->pay_money>$meminfo->max_shopping_money?$info->pay_money:$meminfo->max_shopping_money),
                    'min_shopping_money'=>($info->pay_money<$meminfo->min_shopping_money?$info->pay_money:$meminfo->min_shopping_money),
                    'last_shopping_at'=>$info->create_at
                ]);


                //计算绩效？
                //订单成功发送短信
                // $info->mem_id>0 && WxaccountMessage::sendwx($cp_id, $info->mem_id, 'order'); //收支流水
                Financial::createMoneyLog($cp_id,$info,$info->pay_money,-1);

            }




            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '订单审核成功']);

    }

    /**
     * 审核取消
     */
    public function doorderauditcancel(Request $request)
    {
        $id = $request->id ?? 0;
        $audit_remark=$request->audit_remark ?? '';
        if($audit_remark==''){
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if (($accountinfo['type']==1 || $accountinfo['type']==2) && date('Y-m-d',$info->create_at)!=date('Y-m-d')) {

            return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
        }


        if ($info->audit_status != 1) {
            return response()->json(['code' => '001', 'msg' => '该订单已审核']);
        }

        // if ($info->is_maker != 1) {
        //     return response()->json(['code' => '001', 'msg' => '该订单挂单中不可审核']);
        // }
        OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['audit_status' => 3, 'audit_at' => time(),'audit_remark'=>$audit_remark]);
        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }


    public function doorderauditcancelmore(Request $request){
        $ids = $request->ids;
        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);
        $audit_remark=$request->audit_remark ?? '';
        if($audit_remark==''){
            return response()->json(['code' => '001', 'msg' => '请输入撤单原因']);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];

        $info_more_arr = OrderMaintenance::where(['cp_id' => $cp_id, 'audit_status'=>1])->whereIn('id', $ids)->get();

        if (count($info_more_arr) != count($ids)) {
            return response()->json(['code' => '001', 'msg' => '存在已审核订单']);
        }


        if ($accountinfo['type']==1 || $accountinfo['type']==2) {
            $info_more_count = OrderMaintenance::where(['cp_id' => $cp_id, 'audit_status'=>1])->where([['create_at','>=',strtotime(date('Y-m-d').'00:00:00')],['create_at','<=',time()]])
            ->whereIn('id', $ids)->count();
            if($info_more_count!=count($ids)){
                return response()->json(['code' => '001', 'msg' => '店长只可撤单当日订单']);
            }


        }

        OrderMaintenance::where(['cp_id' => $cp_id, 'is_del' => 1, 'audit_status'=>1])->whereIn('id', $ids)->update(['audit_status' => 3, 'audit_at' => time(),'audit_remark'=>$audit_remark]);
        return response()->json(['code' => '000', 'msg' => '订单撤销成功']);
    }

    /**
     * 导出
     */
    public function doexport(Request $request)
    {
        $request['isgetall'] = 1;
        $list = OrderMaintenance::getList($request)['list'];

        $row = [
            ['table_header'=>'维修开单'],
            [
            'store' => '所属门店',
            'mobile' => '会员电话',
            'real_name' => '会员姓名',
            'mem_card_no' => '会员卡号',
            'desc' => '维修内容',
            'money' => '金额',
            'remark' => '备注',
            'update_account_real_name' => '操作人',
            'update_at' => '操作时间',
        ]];

        $exceldata = [];
        foreach ($list as $val) {
            $exceldata[] = [
                'store' => $val['storeinfo']['store_name'],
                'mobile' => $val['memberinfo']?$val['memberinfo']['mobile']:'',
                'real_name' => $val['memberinfo']?$val['memberinfo']['real_name']:'',
                'mem_card_no' => $val['memberinfo']?$val['memberinfo']['mem_card_no']:'',
                'desc' => $val['desc'],
                'money' => $val['money'] / 100,
                'remark' => $val['remark'],
                'update_account_real_name' => $val['update_account_real_name'],
                'update_at' => date('Y-m-d H:i:s', $val['update_at']),
            ];
        }

        $filename = '维修开单信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }


    /**
     * 更改会员信息
     */
    public function changememinfo(Request $request)
    {
        $req_data = $request->only(['id', 'mobile', 'mem_card_no', 'real_name','lunar_bdate','solar_bdate']);
        $Validate = new ValidateOrderOrderSales('checkmember');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $id=$req_data['id'];
        $info = OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        if($info->balance_money>0){
            return response()->json(['code' => '001', 'msg' => '订单使用预存金额，无法更改']);
        }


        $meminfo = Member::where(['cp_id' => $cp_id, 'mobile' => $req_data['mobile'],'is_del'=>1])->first();

        if($info->mem_id>0){

            DB::beginTransaction();
            try {
               if($meminfo){
                    $data=[];
                    $data['mobile']=isset($req_data['mobile'])?$req_data['mobile']:'';
                    $data['mem_card_no']=isset($req_data['mem_card_no'])?$req_data['mem_card_no']:'';
                    $data['real_name']=isset($req_data['real_name'])?$req_data['real_name']:'';
                    $data['lunar_bdate']=isset($req_data['lunar_bdate'])?$req_data['lunar_bdate']:'';
                    $data['solar_bdate']=isset($req_data['solar_bdate'])?$req_data['solar_bdate']:'';
                    Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id,'is_del'=>1])->update($data);


                    OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id'=>$meminfo->id]);
                }else{
                    $data=[
                        'create_at' => time(),
                        'update_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                    ];
                    $data['cp_id']=$cp_id;
                    $data['store_id']=$info->store_id;

                    $data['mobile']=isset($req_data['mobile'])?$req_data['mobile']:'';
                    $data['mem_card_no']=isset($req_data['mem_card_no'])?$req_data['mem_card_no']:'';
                    $data['real_name']=isset($req_data['real_name'])?$req_data['real_name']:'';
                    $data['lunar_bdate']=isset($req_data['lunar_bdate'])?$req_data['lunar_bdate']:'';
                    $data['solar_bdate']=isset($req_data['solar_bdate'])?$req_data['solar_bdate']:'';
                    $ins_mem_id=Member::create($data)->id;
                    CommonMember::setMemInitPoints($request,$ins_mem_id);

                    OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id'=>$ins_mem_id]);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '会员信息绑定失败' . $e->getMessage()]);
            }





            return response()->json(['code' => '000', 'msg' => '会员信息变更成功']);
        }else{
            DB::beginTransaction();
            try {
                if($meminfo){

                    $data=[];
                    $data['mobile']=isset($req_data['mobile'])?$req_data['mobile']:'';
                    $data['mem_card_no']=isset($req_data['mem_card_no'])?$req_data['mem_card_no']:'';
                    $data['real_name']=isset($req_data['real_name'])?$req_data['real_name']:'';
                    $data['lunar_bdate']=isset($req_data['lunar_bdate'])?$req_data['lunar_bdate']:'';
                    $data['solar_bdate']=isset($req_data['solar_bdate'])?$req_data['solar_bdate']:'';
                    Member::where(['cp_id' => $cp_id, 'id' => $meminfo->id,'is_del'=>1])->update($data);

                    OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id'=>$meminfo->id]);
                }else{
                    $data=[
                        'create_at' => time(),
                        'update_at' => time(),
                        'create_account_id' => $accountinfo['id'],
                        'update_account_id' => $accountinfo['id'],
                        'create_account_real_name' => $accountinfo['real_name'],
                        'update_account_real_name' => $accountinfo['real_name'],
                    ];
                    $data['cp_id']=$cp_id;
                    $data['store_id']=$info->store_id;

                    $data['mobile']=isset($req_data['mobile'])?$req_data['mobile']:'';
                    $data['mem_card_no']=isset($req_data['mem_card_no'])?$req_data['mem_card_no']:'';
                    $data['real_name']=isset($req_data['real_name'])?$req_data['real_name']:'';
                    $data['lunar_bdate']=isset($req_data['lunar_bdate'])?$req_data['lunar_bdate']:'';
                    $data['solar_bdate']=isset($req_data['solar_bdate'])?$req_data['solar_bdate']:'';
                    $ins_mem_id=Member::create($data)->id;
                    CommonMember::setMemInitPoints($request,$ins_mem_id);
                    OrderMaintenance::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['mem_id'=>$meminfo->id]);
                }

                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return response()->json(['code' => '001', 'msg' => '会员信息绑定失败' . $e->getMessage()]);
            }
            return response()->json(['code' => '000', 'msg' => '会员信息绑定成功']);
        }





    }

    public function getorderprintdata(Request $request){
        $id = $request->id ?? 0;
        $cp_id = StoreCommon::getCurrentAccountCompanyId($request);
        if($id<=0){
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        $data=ServicesOrderOrderMaintenance::getOrderPrintData($id);
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>$data]);
    }
}
